const { chromium } = require('playwright');
const fs = require('fs').promises;

module.exports = async (url, outputPath) => {
    const browser = await chromium.launch({
        executablePath: 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
        ignoreHTTPSErrors: true // 关键配置：忽略HTTPS错误
    });

    const context = await browser.newContext({
        ignoreHTTPSErrors: true, // 上下文也需要设置
        bypassCSP: true // 可选：绕过内容安全策略
    });

    const page = await context.newPage();
    
    await page.setViewportSize({ width: 1920, height: 1080 })
    let response;

    try {
        // 设置超时和等待选项
        response = await page.goto(url, {
            waitUntil: 'domcontentloaded',
            timeout: 30000,
            // 可以添加重试逻辑
            retries: 2,
            retryDelay: 1000
        });

        // 处理证书错误页面的继续访问
        if (response && response.status() === 0) {
            // 有些证书错误会返回状态码0
            await page.evaluate(() => {
                // 尝试模拟点击"高级"->"继续前往"按钮
                const selector = 'button#details-button, button#proceed-link, a#proceed-link';
                const btn = document.querySelector(selector);
                if (btn) btn.click();
            });

            // 等待页面真正加载
            await page.waitForNavigation({ waitUntil: 'networkidle' });
        }

        // 截图
        await page.screenshot({ path: outputPath});
        const fileBuffer = await fs.readFile(outputPath);

        return {
            status: response?.status() || 200, // 如果绕过证书错误，默认返回200
            buffer: fileBuffer,
            path: outputPath,
            size: fileBuffer.length,
            mimeType: 'image/png',
            securityWarningBypassed: true // 标记已绕过安全警告
        };

    } catch (error) {
        console.error('截图失败:', error);
        throw error;
    } finally {
        await browser.close();
    }
};